<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>车辆管理</title>
    <link rel="stylesheet" type="text/css"
          href="${pageContext.request.contextPath}/js/jquery-easyui-1.4.1/themes/default/easyui.css"/>
    <link rel="stylesheet" type="text/css"
          href="${pageContext.request.contextPath}/js/jquery-easyui-1.4.1/themes/icon.css"/>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/js/jquery-easyui-1.4.1/jquery.min.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/js/jquery-easyui-1.4.1/jquery.easyui.min.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/js/jquery-easyui-1.4.1/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/common.js"></script>
    <script type="text/javascript">
        /* 添加管理列 */

        //当前线路id
        var lineIds = 0;

        //映射 管理按钮
        function fmtmake(val, row) {
            // alert(row.lineId);
            // alert(row.lineName);
            var make = '<a href="javascript:void(0);" onclick="manageSite(' + row.lineId + ')" >管理站点</a>';
            make += ' ' + '<a href="javascript:void(0);" onclick="linemanagebus(' + row.lineId + ')" >分配车辆</a>';
            return make;
        }

        /* 打开line管理页面 */
        function manageSite(lineId) {
            $('#lineManage').window('open').dialog('setTitle', '管理线路站点');
            $('#siteList').datagrid({
                url: '${pageContext.request.contextPath}/busSite/querySingleLine',
                queryParams: {
                    lineId: lineId
                }
            });
            lineIds = lineId;
        }

        /* 打开分配车辆页面 */
        function linemanagebus(lineId) {
            $('#lineManageBus').window('open').dialog('setTitle', '管理路线的公交车');
            $('#busList').datagrid({
                url: '${pageContext.request.contextPath}/bus/all'
            });
            lineIds = lineId;
        }

        /* 映射车队名称 */
        function fmtTeamName(val, row) {
            return row.busTeam.teamName;
        }

        /* 映射车队Id */
        function fmtTeamId(val, row) {
            return row.busTeam.teamId;
        }

        /* 默认选中本车队Id */
        /* function defaultchoase(){
            var row = $("#busList").datagrid('getRows');
            console.log(row);
            for (var i = 0; i < row.length; i++) {
            console.log(i);
                   if(row[i]['lineId']==lineIds){
                       $('#busList').datagrid('selectRow',1);
                   }
              }
        } */

        //车辆管理搜索
        function querybusline() {
            var busNumber = $('#selectbus').val();
            $('#busList').datagrid({
                url: '${pageContext.request.contextPath}/bus/all',
                queryParams: {
                    busNumber: busNumber
                }
            });
        }

        /* 车辆保存按钮 */
        function saveLine() {
            var v = getSelectionsIds3();
            $.post("${pageContext.request.contextPath}/bus/updateLineIdOfBus", {
                'lineId': lineIds,
                'busIds': v
            }, function (data) {
                if (data.code == 200) {
                    $.messager.alert('提示', '分配线路车辆成功!', undefined, function () {
                        $("#busList").datagrid('reload');
                    });
                } else {
                    $.messager.alert('提示', '分配线路车辆失败!', undefined, function () {
                        $("#busList").datagrid('reload');
                    });
                }
            }, "json");
        }

        //获取选中管理路线公交车的id
        function getSelectionsIds3() {
            var lineList = $("#busList");
            var sels = lineList.datagrid("getSelections");
            console.log(sels);
            var ids = [];
            for (var i in sels) {
                ids.push(sels[i].busId);
            }
            ids = ids.join(",");
            return ids;
        }

        //上行  下行  显示
        function toplow(upDown) {
            $('#siteList').datagrid({
                url: '${pageContext.request.contextPath}/busSite/querySingleLine',
                queryParams: {
                    lineId: lineIds,
                    upDown: upDown
                }
            });
        }

        //映射上移 下移按钮
        function fmtmake2(val, row, index) {
            var str = "";
            str += '<a href="javascript:void(0);" onclick="moveup(' + index + ')">上移</a>';
            str += ' ';
            str += '<a href="javascript:void(0);" onclick="movedown(' + index + ')">下移</a>';
            str += ' ';
            str += '<a href="javascript:void(0);" onclick="view(' + row.lineId + ')">详情</a>';
            str += ' ';
            return str;
        }

        function view() {
            $.messager.alert("提示","请到站点管理模块查看")
        }

        //下移
        function movedown(index) {
            var row = $("#siteList").datagrid('getSelected');
            mysort(index, "down", "siteList");
        }

        //上移
        function moveup(index) {
            var row = $("#siteList").datagrid("getSelected");
            mysort(index, "up", "siteList");
        }

        function mysort(index, type, gridname) {
            $("#moveshow").show();
            if ("up" == type) {
                if (index != 0) {
                    var toup = $("#" + gridname).datagrid('getData').rows[index];
                    var todown = $("#" + gridname).datagrid('getData').rows[index - 1];
                    $("#" + gridname).datagrid('getData').rows[index] = todown;
                    $("#" + gridname).datagrid('getData').rows[index - 1] = toup;
                    $("#" + gridname).datagrid('refreshRow', index);
                    $("#" + gridname).datagrid('refreshRow', index - 1);
                    $("#" + gridname).datagrid('selectRow', index - 1);
                }
            } else if ("down" == type) {
                var rows = $("#" + gridname).datagrid("getRows").length;
                if (index != rows - 1) {
                    var todown = $("#" + gridname).datagrid("getData").rows[index];
                    var toup = $("#" + gridname).datagrid("getData").rows[index + 1];
                    $("#" + gridname).datagrid("getData").rows[index + 1] = todown;
                    $("#" + gridname).datagrid("getData").rows[index] = toup;
                    $("#" + gridname).datagrid("refreshRow", index);
                    $("#" + gridname).datagrid("refreshRow", index + 1);
                    $("#" + gridname).datagrid("selectRow", index + 1);
                }

            }
        }

        /* 保存按钮 */
        function save() {
            var rows = $("#siteList").datagrid('getRows')//获取当前页的数据行
            var total = "";
            for (var i = 0; i < rows.length; i++) {
                total += rows[i]['siteId']; //获取指定列
                if (i != rows.length - 1) {
                    total += ",";
                }
            }
            console.log(total);
            $.post("${pageContext.request.contextPath}/busLine/updateIndex", {
                'siteIds': total,
                'lineId': lineIds
            }, function (data) {
                if (data.code == 200) {
                    $.messager.alert('提示', '修改站点顺序成功!', undefined, function () {
                        $("#siteList").datagrid('reload');
                    });
                } else {
                    $.messager.alert('提示', '修改站点顺序失败!', undefined, function () {
                        $("#siteList").datagrid('reload');
                    });
                }
                $("#moveshow").hide();
            }, "json");
        }

        //删除线路上的站点
        function deleteSite() {
            var siteIds = getSelectionsIds2();
            $.messager.confirm('确认', '确定从本路线上移除id为 ' + siteIds + ' 的站点吗？', function (r) {
                if (r) {
                    console.log(siteIds);
                    $.post("${pageContext.request.contextPath}/busLine/deleteSite", {
                        'siteIds': siteIds,
                        'lineId': lineIds
                    }, function (data) {
                        if (data.code == 200) {
                            $.messager.alert('提示', '删除站点顺序成功!', undefined, function () {
                                $("#siteList").datagrid('reload');
                            });
                        } else {
                            $.messager.alert('提示', '删除站点顺序失败!', undefined, function () {
                                $("#siteList").datagrid('reload');
                            });
                        }
                    }, "json");

                }
            })
        }

        //获取管理路线的id
        function getSelectionsIds2() {
            var lineList = $("#siteList");
            var sels = lineList.datagrid("getSelections");
            var ids = [];
            for (var i in sels) {
                ids.push(sels[i].siteId);
            }
            ids = ids.join(",");
            return ids;
        }

        function formatSet(val, row) {
            if (val == 1) {
                return "运行";
            } else if (val == 0) {
                return "停运";
            }
        }

        function fmtPrice(val, row) {
            return val + "元";
        }

        //获取路线的id
        function getSelectionsIds() {
            var lineList = $("#lineList");
            var sels = lineList.datagrid("getSelections");
            var ids = [];
            for (var i in sels) {
                ids.push(sels[i].lineId);
            }
            ids = ids.join(",");
            return ids;
        }

        //将时间戳转换为正常的时间格式

        function timestampToTime(timestamp) {
            var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = date.getDate() + ' ';
            var h = date.getHours() + ':';
            var m = date.getMinutes() + ':';
            var s = date.getSeconds();
            return Y + M + D;
        };
        var toolbar = [{
            text: '线路名称：<input id = "serach1" class="search" style="width:60px;"/>',
        }, {
            text: '所属车队：<input id = "serach2" class="search" style="width:80px;"/>',
        }, {
            text: '搜索',
            iconCls: 'icon-search',
            handler: function () {
                var lineName = $("#serach1").val();
                var teamName = $("#serach2").val();
                $("#lineList").datagrid("load", {
                    lineName: lineName,
                    teamName: teamName
                });
            }
        }, {
            text: '新增',
            iconCls: 'icon-add',
            handler: function () {
                $('#lineAdd').window('open');
            }
        }, {
            text: '编辑',
            iconCls: 'icon-edit',
            handler: function () {
                var ids = getSelectionsIds();
                if (ids.length == 0 || ids.length > 1) {
                    $.messager.alert('提示', '还未选中要修改的线路,或者选择了多个线路');
                    return;
                }
                $.messager.confirm('确认', '确定要修改ID为' + ids + '的线路吗？', function (r) {
                    if (r) {
                        $('#lineUpdate').window({
                            onLoad: function () {
                                var lineList = $("#lineList");
                                /* 由于获取到的user是一个数组，这里必须加上【0】 */
                                var line = lineList.datagrid("getSelections")[0];
                                $("#content").form("load", {
                                    lineId: line.lineId,
                                    lineName: line.lineName,
                                    teamName: line.busTeam.teamId
                                });
                                /* 给隐藏标签，设置id,问题就是只在页面加载的时候赋值一次，不能每次选择后都重新赋值 */
                                // $('#teamName1').val(line.busCompany.companyId);
                            }
                        }).window('open');
                    }
                });
            }
        }, {
            text: '删除',
            iconCls: 'icon-cancel',
            handler: function () {
                var ids = getSelectionsIds();
                if (ids.length == 0) {
                    $.messager.alert('提示', '未选中线路!');
                    return;
                }
                $.messager.confirm('确认', '确定删除ID为 ' + ids + ' 的线路吗？', function (r) {
                    if (r) {
                        $.post("${pageContext.request.contextPath}/busLine/delete", {'lineIds': ids}, function (data) {
                            if (data.code == 200) {
                                $.messager.alert('提示', '删除线路成功!', undefined, function () {
                                    $("#lineList").datagrid('reload');
                                });
                            } else {
                                $.messager.alert('提示', '删除线路失败!', undefined, function () {
                                    $("#lineList").datagrid('reload');
                                });
                            }
                        }, "json");
                    }
                });
            }
        }, '-', {
            text: '导出',
            iconCls: 'icon-remove',
            handler: function () {
                var options = $("#lineList").datagrid("getPager").data("pagination").options;
                var page = options.pageNumber;
                var rows = options.pageSize;
                $("<form>").attr({
                    "action": "${pageContext.request.contextPath}/line/export/lineExcel",
                    "method": "POST"
                }).append("<input type='hidden' name='page' value='" + page + "' />")
                    .append("<input type='hidden' name='rows' value='" + rows + "' />").appendTo("body").submit();
            }
        }];

        //上行 下行  按钮 css样式
        $(document).ready(function () {
            $("#left a").click(function () {
                $(this).css("background-color", "blue");
                $(this).siblings().css("background-color", "#C0C0C0");
            });
        })

    </script>
</head>
<body>
<div>
    <table class="easyui-datagrid" id="lineList"
           data-options="singleSelect:false,collapsible:true,pagination:true,url:'${pageContext.request.contextPath}/busLine/lineList',method:'post',pageSize:5,toolbar:toolbar,pageList:[2,5,10],rownumbers:true">

        <thead>
        <tr>
            <th data-options="field:'ck',checkbox:true"></th>
            <th data-options="field:'lineId',align:'center',width:20,hidden:true">ID</th>
            <th data-options="field:'lineMade',align:'center',width:120,formatter:fmtmake">操作</th>
            <th data-options="field:'lineName',align:'center',width:200">线路名称</th>
            <th data-options="field:'teamName',align:'center',width:100,formatter:fmtTeamName">所属车队
            </th>
            <th data-options="field:'lineStatus',width:130,align:'center',formatter:formatSet">运行状态
            </th>
            <th data-options="field:'linePrice',width:130,align:'center',formatter:fmtPrice">价格
            </th>
        </tr>
        </thead>
    </table>
</div>
<div id="lineAdd" class="easyui-window" title="新增线路"
     data-options="modal:true,closed:true,iconCls:'icon-save',href:'${pageContext.request.contextPath}/to/line-add'"
     style="width:700px;height:300px;padding:10px;top: 50px"></div>
<div id="lineUpdate" class="easyui-window" title="修改路线"
     data-options="model:true,closed:true,iconCls:'icon-update',href:'${pageContext.request.contextPath}/to/line-update'"
     style="width:700px;height:300px;padding:10px;top: 50px"></div>

<!-- 管理路线弹出框 -->
<div id="lineManage" class="easyui-window"
     data-options="model:true,closed:true,iconCls:'icon-update',modal:true"
     style="width:800px;height:400px;padding:10px;top: 50px">
    <div id="" class="easyui-layout" style="width:100%;height:100%;"
         data-options="border:false">
        <div data-options="region:'west',border:false"
             style="width:50px;font-size: 20px; color: white;" id="left">
            <a href="javascript:void(0);" onclick="toplow(0)"
               class="easyui-linkbutton" data-options="plain:true"
               style="background-color: blue;color: white;width:50px;">上行</a> <a
                href="javascript:void(0);" onclick="toplow(1)"
                class="easyui-linkbutton" data-options="plain:true"
                style="background-color: #C0C0C0;color: white;width:50px;">下行</a>
        </div>
        <div data-options="region:'center'">
            <table class="easyui-datagrid" id="siteList"
                   data-options="method:'post',striped:true,fitColumns:true,rownumbers:true,toolbar:'#siteline'">
                <thead>
                <tr>
                    <th data-options="field:'ck',checkbox:true"></th>
                    <th data-options="field:'lineMade',width:120,formatter:fmtmake2">操作</th>
                    <th data-options="field:'siteId',width:200,hidden:true">站点Id</th>
                    <th data-options="field:'siteName',width:200">站点名称</th>
                    <th data-options="field:'upDown',width:200">站点方向</th>
                </tr>
                </thead>
            </table>
        </div>

        <div data-options="border:false" id="siteline">
            <input type="button" value="批量删除" onclick="deleteSite()" id="delete"> <input
                type="button" value="保存" id="moveshow" onclick="save()"
                style="display: none;">
        </div>
    </div>
</div>

<!-- 分配车辆弹出框 -->
<div id="lineManageBus" class="easyui-window" data-options="model:true,closed:true,iconCls:'icon-update',modal:true"
     style="width:700px;height:400px;padding:10px;top: 50px">
    <div data-options="region:'center'">
        <table class="easyui-datagrid" id="busList"
               data-options="pagination:true,method:'post',striped:true,fitColumns:true,rownumbers:true,toolbar:'#busSite',pageSize:10,pageList:[2,5,10]">
            <thead>
            <tr>
                <th data-options="field:'ck',checkbox:true"></th>
                <th data-options="field:'busId',width:200,hidden:true">公交车Id</th>
                <th data-options="field:'busNumber',width:200">车牌号</th>
                <th data-options="field:'teamId',width:200,hidden:true,formatter:fmtTeamId">所属车队id</th>
                <th data-options="field:'teamName',width:200,formatter:fmtTeamName">所属车队</th>
            </tr>
            </thead>
        </table>
    </div>
    <div data-options="border:false" id="busSite">
        <input type="text" id="selectbus">
        <input type="button" onclick="querybusline()" value="搜索车辆"></input>
        <input type="button" value="保存" onclick="saveLine()">
    </div>
</div>
</body>
</html>